<template>
  <div class="business-info-edit">
    <div class="header">
      <h2><i class="fa fa-edit"></i> 店铺信息编辑</h2>
      <button @click="saveBusinessInfo" :disabled="isSaving" class="save-button">
        {{ isSaving ? '保存中...' : '保存修改' }}
      </button>
    </div>

    <div class="business-form">
      <div class="form-section">
        <div class="form-group">
          <label>店铺名称</label>
          <input v-model="business.businessName" placeholder="请输入店铺名称">
        </div>

        <div class="form-group">
          <label>登录密码</label>
          <input type="password" v-model="business.password" placeholder="请输入新密码（留空则不修改）">
        </div>

        <div class="form-group">
          <label>店铺地址</label>
          <input v-model="business.businessAddress" placeholder="请输入详细地址">
        </div>
      </div>

      <div class="form-section">
        <div class="form-group">
          <label>店铺图片</label>
          <div class="image-upload">
            <img v-if="previewImage" :src="previewImage" class="preview-image">
            <img v-else-if="business.businessImg" :src="'data:image/jpeg;base64,' + business.businessImg" class="preview-image">
            <div v-else class="image-placeholder">
              <i class="fa fa-picture-o"></i>
              <span>暂无图片</span>
            </div>
            <label for="image-upload" class="upload-button">
              {{ previewImage || business.businessImg ? '更换图片' : '选择图片' }}
            </label>
            <input 
              type="file" 
              id="image-upload" 
              accept="image/*" 
              @change="handleImageUpload"
              class="file-input"
            >
          </div>
        </div>
      </div>

      <div class="form-section">
        <div class="form-group">
          <label>店铺介绍</label>
          <textarea v-model="business.businessExplain" placeholder="店铺简介" rows="4"></textarea>
        </div>
      </div>

      <div class="form-section">
        <div class="form-group">
          <label>分类</label>
          <select v-model="business.orderTypeId">
            <option value="1">美食</option>
            <option value="2">早餐</option>
            <option value="3">跑腿代购</option>
            <option value="4">汉堡拔萨</option>
            <option value="5">甜品饮品</option>
            <option value="6">速食简餐</option>
            <option value="7">地方小吃</option>
            <option value="8">米粉面馆</option>
            <option value="9">包子粥铺</option>
            <option value="10">炸鸡炸串</option>
          </select>
        </div>

        <div class="form-group">
          <label>起送费</label>
          <input type="number" v-model="business.starPrice" placeholder="起送价格" min="0" step="0.01">
        </div>

        <div class="form-group">
          <label>配送费</label>
          <input type="number" v-model="business.deliveryPrice" placeholder="配送费用" min="0" step="0.01">
        </div>
      </div>

      <div class="form-section">
        <div class="form-group">
          <label>备注信息</label>
          <textarea v-model="business.remarks" placeholder="备注信息" rows="2"></textarea>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BusinessInfoEdit',
  data() {
    return {
      business: {
        businessId: 0,
        businessName: '',
        password: '',
        businessAddress: '',
        businessExplain: '',
        businessImg: '',
        orderTypeId: 1,
        starPrice: 0,
        deliveryPrice: 0,
        remarks: ''
      },
      previewImage: null,
      newImageBase64: null,
      isSaving: false
    }
  },
  created() {
    this.loadBusinessInfo();
  },
  methods: {
    async loadBusinessInfo() {
      const businessId = this.$route.query.businessId;
      if (!businessId) {
        alert('缺少商家ID');
        this.$router.go(-1);
        return;
      }

      try {
        const response = await this.$axios.post(
          'BusinessController/getBusinessById',
          this.$qs.stringify({ businessId })
        );
        
        if (response.data) {
          this.business = response.data;
        } else {
          alert('获取商家信息失败');
          this.$router.go(-1);
        }
      } catch (error) {
        console.error('加载商家信息失败:', error);
        alert('加载商家信息失败');
        this.$router.go(-1);
      }
    },
    
    handleImageUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      if (!file.type.match('image.*')) {
        alert('请选择图片文件');
        return;
      }
      
      if (file.size > 2 * 1024 * 1024) {
        alert('图片大小不能超过2MB');
        return;
      }
      
      // 预览图片
      const reader = new FileReader();
      reader.onload = (e) => {
        this.previewImage = e.target.result;
      };
      reader.readAsDataURL(file);
      
      // 转换为Base64
      const base64Reader = new FileReader();
      base64Reader.onload = (e) => {
        const base64Data = e.target.result.split(',')[1];
        this.newImageBase64 = base64Data;
      };
      base64Reader.readAsDataURL(file);
    },
    
    async saveBusinessInfo() {
		
          // 基本验证
          if (!this.business.businessName || !this.business.businessName.trim()) {
            alert('店铺名称不能为空');
            return;
          }
          
          this.isSaving = true;
          
          try {
            // 创建更新对象 - 只包含需要更新的字段
            const updateData = {
              businessId: this.business.businessId,
			  password: this.business.password,
              businessName: this.business.businessName,
              businessAddress: this.business.businessAddress,
              businessExplain: this.business.businessExplain,
              orderTypeId: this.business.orderTypeId,
              starPrice: this.business.starPrice,
              deliveryPrice: this.business.deliveryPrice,
              remarks: this.business.remarks
            };
            
            // 如果上传了新图片
            if (this.newImageBase64) {
              updateData.businessImg = this.newImageBase64;
            }
            
            // 如果有新密码
            if (this.business.password && this.business.password.trim()) {
              updateData.password = this.business.password;
            }
            
            console.log('提交更新数据:', updateData);
            
            const response = await this.$axios.post(
              'BusinessController/updateBusiness',
              this.$qs.stringify(updateData),
              {
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                }
              }
            );
            
            console.log('更新响应:', response);
            
            if (response.data && response.data.success) {
              alert('店铺信息更新成功！');
              
              // 更新本地存储的商家信息
              const currentBusiness = this.$getSessionStorage('business');
              if (currentBusiness && currentBusiness.businessId === this.business.businessId) {
                const updatedBusiness = {
                  ...currentBusiness,
                  businessName: this.business.businessName,
                  businessImg: this.newImageBase64 || this.business.businessImg
                };
                this.$setSessionStorage('business', updatedBusiness);
              }
              
              // 如果返回了完整的更新数据，使用它更新当前页面
              if (response.data.business) {
                this.business = response.data.business;
                this.newImageBase64 = null; // 重置新图片标记
              }
              
              // 返回商家首页
              this.$router.push('/businessHome');
            } else {
              const errorMsg = response.data?.message || '更新失败，请重试';
              alert(errorMsg);
            }
          } catch (error) {
            console.error('更新错误:', error);
            let errorMessage = '更新过程中发生错误';
            
            if (error.response) {
              if (error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message;
              } else {
                errorMessage = `服务器错误: ${error.response.status}`;
              }
            }
            
            alert(errorMessage);
          } finally {
            this.isSaving = false;
          }
    }
  }
}
</script>

<style scoped>
.business-info-edit {
  max-width: 800px;
  margin: 30px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.header h2 {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #2c3e50;
  font-size: 24px;
}

.save-button {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.save-button:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
}

.save-button:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.business-form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 25px;
}

.form-section {
  background: #f9fafb;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #34495e;
}

input, textarea, select {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 15px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

input:focus, textarea:focus, select:focus {
  border-color: #3498db;
  outline: none;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.image-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.preview-image {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.image-placeholder {
  width: 150px;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  color: #a1a8b3;
}

.image-placeholder i {
  font-size: 40px;
  margin-bottom: 10px;
}

.upload-button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.upload-button:hover {
  background-color: #e4e7ed;
  border-color: #c0c4cc;
}

.file-input {
  display: none;
}

@media (max-width: 768px) {
  .business-form {
    grid-template-columns: 1fr;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>